﻿using System;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Windows.Forms;
using AppAcc.Models;
//using AppAcc.Views.BaoCaoChungTu;
using AppAcc.Views.DanhMuc;
using System.Data.SqlClient;
using Microsoft.Reporting.WinForms;

namespace AppAcc.Views.KTVTienMat
{
    public partial class FormPhieuChiChinhSua : DevComponents.DotNetBar.RibbonForm
    {
        public FormPhieuChiChinhSua()
        {
            InitializeComponent();
        }
        //private AppAccContext db = new AppAccContext();
        private PhanMenKeToanEntities1 db = new PhanMenKeToanEntities1();
        public string idct = "";
        private int indexrow = 0;
        private decimal idctct = 0;
        private string listIdChiTietCanXoa = "";
        private int soRowXoa = 0;
        private bool co = false;
        #region Event
        private void FormPhieuChiChinhSua_Load(object sender, EventArgs e)
        {
            FillDataChungTu();

            if (idct != "")
            {
                var ct = db.ChungTus.Find(idct);
                txtChungTu.Text = ct.Id;
                txtChungTu.Enabled = false;
                txtSoChungTuGoc.Text = ct.SoChungTuGoc;
                txtNoiDung.Text = ct.NoiDung;
                cbbNhanVien.SelectedValue = ct.NhanVienId;
                cbbDoiTac.SelectedValue = ct.DoiTacId;
                dtiNgayChungTu.Value = ct.NgayChungTu;
                dtiNgayLapPhieu.Value = ct.NgayLapPhieu;
                GetDataChiTietChungTu();
                FillTaiKhoan();
                co = true;
                KiemTra();
            }
            else
            {
                MessageBox.Show("Không tải được dữ liệu!");
                this.Close();
            }
        }

        private void cbbNhomNhaCungCap_SelectedIndexChanged(object sender, EventArgs e)
        {
            var index = Convert.ToInt32(cbbNhomNhaCungCap.SelectedIndex);
            if (index < 1) return;
            var id = Convert.ToInt32(cbbNhomNhaCungCap.SelectedValue);
            cbbDoiTac.DataSource = db.DoiTacs.Where(t => t.NhomDoiTacId == id).ToList();
            cbbDoiTac.DisplayMember = "TenDoiTac";
            cbbDoiTac.ValueMember = "Id";
            cbbDoiTac.Enabled = true;
        }

        private void cbbDoiTac_SelectedIndexChanged(object sender, EventArgs e)
        {
            KiemTra();
        }

        private void cbbNhanVien_SelectedIndexChanged(object sender, EventArgs e)
        {
            KiemTra();
        }

        private void txtNoiDung_TextChanged(object sender, EventArgs e)
        {
            KiemTra();
        }

        private void dtiNgayChungTu_TextChanged(object sender, EventArgs e)
        {
            KiemTra();
        }

        private void dtiNgayLapPhieu_TextChanged(object sender, EventArgs e)
        {
            KiemTra();
        }

        private void bttThemMoiNhanVien_Click(object sender, EventArgs e)
        {
            var f = new FormNhanVien();
            f.ShowDialog();
        }

        private void bttThemMoiNhaCungCap_Click(object sender, EventArgs e)
        {
            var f = new FormDoiTac();
            f.ShowDialog();
        }

        private void bttThemMoi_Click(object sender, EventArgs e)
        {
            var f = new FormPhieuChiThemMoi();
            f.ShowDialog();
            this.Close();
        }

        private void bttLuu_Click(object sender, EventArgs e)
        {
            Edit();
        }

        private void bttLuu_Thoat_Click(object sender, EventArgs e)
        {
            Edit();
            this.Close();
        }

        private void bttLuu_ThemMoi_Click(object sender, EventArgs e)
        {
            Edit();
            var f = new FormPhieuChiThemMoi();
            f.ShowDialog();
            this.Close();
        }

        private void bttInChungTu_Click(object sender, EventArgs e)
        {
            Views.BaoCao.FormBaoCaoChungTuKeToan f = new BaoCao.FormBaoCaoChungTuKeToan(txtChungTu.Text);
            f.ShowDialog();
        }

        private void bttThoat_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void dgvChiTietChungTu_MouseDown(object sender, MouseEventArgs e)
        {

            if (e.Button != MouseButtons.Right) return;
            var ht = dgvChungTuChiTiet.HitTest(e.X, e.Y);
            var rowindex = ht.RowIndex;// get id chi tiet phieu tang tscd
            indexrow = rowindex;
            var row = dgvChungTuChiTiet.Rows[rowindex];
            idctct = Convert.ToDecimal(row.Cells[0].Value);
            var rowcount = dgvChungTuChiTiet.RowCount;
            if (ht.ColumnIndex != -1 && ht.RowIndex == rowcount - 1)
            {
                //New menu strip 
                var Menu = new ContextMenuStrip();
                //var chen = new ToolStripMenuItem("Chèn (Ins)");//new button
                //chen.MouseDown += new MouseEventHandler(CmsChenDong_Click);// add event to button
                var xoa = new ToolStripMenuItem("Xóa (Del)");
                xoa.MouseDown += new MouseEventHandler(CmsXoaDong_Click);
                //Menu.Items.AddRange(new ToolStripItem[] { chen });//add button to menu strip
                Menu.Items.AddRange(new ToolStripItem[] { xoa });
                //add menu to datagridview
                dgvChungTuChiTiet.ContextMenuStrip = Menu;
            }
            else
                dgvChungTuChiTiet.ContextMenuStrip = null;
        }
        private void CmsChenDong_Click(object sender, EventArgs e)
        {
            var dgwr = new DataGridViewRow();
            dgvChungTuChiTiet.Rows.Insert(indexrow, dgwr);
        }
        private void CmsXoaDong_Click(object sender, EventArgs e)
        {
            var row = dgvChungTuChiTiet.Rows[indexrow];
            var idrow = row.Cells["Id"].Value.ToString();
            listIdChiTietCanXoa += idrow + "-";
            row.Visible = false;
            soRowXoa += 1;
        }
        private void dgvChiTietChungTu_CellValueChanged(object sender, DataGridViewCellEventArgs e)
        {
            if (co == true)
            {
                KiemTra();
                UpdateAmount(e.ColumnIndex);
                MessageBox.Show(e.ColumnIndex.ToString());
            }
        }
        #endregion Event
        #region Metho
        void FillTaiKhoan()
        {
            var n = dgvChungTuChiTiet.Columns["TaiKhoanNo"] as DataGridViewComboBoxColumn;
            if (n != null)
            {
                n.DataSource = db.TaiKhoans.ToList();
                n.DisplayMember = "Id";
                n.ValueMember = "Id";
            }

            var c = dgvChungTuChiTiet.Columns["TaiKhoanCo"] as DataGridViewComboBoxColumn;
            if (c == null) return;
            c.DataSource = db.TaiKhoans.ToList();
            c.DisplayMember = "Id";
            c.ValueMember = "Id";
        }
        void FillDataChungTu()
        {
            cbbNhanVien.DataSource = db.NhanViens.ToList();
            cbbNhanVien.DisplayMember = "TenNhanVien";
            cbbNhanVien.ValueMember = "Id";

            cbbNhomNhaCungCap.DataSource = db.NhomDoiTacs.ToList();
            cbbNhomNhaCungCap.DisplayMember = "TenNhomDoiTac";
            cbbNhomNhaCungCap.ValueMember = "Id";
            cbbNhomNhaCungCap.SelectedIndex = -1;

            cbbDoiTac.DataSource = db.DoiTacs.ToList();
            cbbDoiTac.DisplayMember = "TenDoiTac";
            cbbDoiTac.ValueMember = "Id";
            cbbDoiTac.Enabled = true;
        }
        void KiemTra()
        {
            if (txtNoiDung.Text != "" && Convert.ToInt32(cbbDoiTac.SelectedValue) != 0 && Convert.ToInt32(cbbNhanVien.SelectedValue) != 0 && dgvChungTuChiTiet.RowCount > 1 && dtiNgayChungTu.Value.ToString().Length > 0 && dtiNgayLapPhieu.Value.ToString().Length > 0)
            {
                bttInChungTu.Enabled = true;
                bttLuu.Enabled = true;
                bttLuu_ThemMoi.Enabled = true;
                bttLuu_Thoat.Enabled = true;
            }
            else
            {
                bttInChungTu.Enabled = false;
                bttLuu.Enabled = false;
                bttLuu_ThemMoi.Enabled = false;
                bttLuu_Thoat.Enabled = false;
            }
        }

        private void Edit()
        {
            var pt = db.ChungTus.Find(idct);
            pt.NgayChungTu = dtiNgayChungTu.Value;
            pt.NgayLapPhieu = dtiNgayLapPhieu.Value;
            pt.NhanVienId = Convert.ToInt32(cbbNhanVien.SelectedValue);
            pt.NoiDung = txtNoiDung.Text;
            pt.SoChungTuGoc = txtSoChungTuGoc.Text;
            pt.TrangThai = pt.TrangThai;
            var co = 0;
            decimal soTienNo = 0;
            decimal soTienCo = 0;
            pt.TongTien = 0;
            var kt = true;
            foreach (DataGridViewRow item in dgvChungTuChiTiet.Rows)
            {
                if (co < (dgvChungTuChiTiet.RowCount - soRowXoa))
                {
                    var ct = db.ChungTuChiTiets.Find(Convert.ToDecimal(item.Cells[0].Value));
                    ct.ChungTuId = pt.Id;
                    if (item.Cells["TaiKhoanNo"].Value != null && item.Cells["TaiKhoanNo"].Value.ToString().Length > 0)
                    {
                        ct.TaiKhoanNo = item.Cells["TaiKhoanNo"].Value.ToString();
                    }
                    else if (item.Cells["TaiKhoanCo"].Value != null && item.Cells["TaiKhoanCo"].Value.ToString().Length > 0)
                    {
                        ct.TaiKhoanCo = item.Cells["TaiKhoanCo"].Value.ToString();
                    }
                    if (item.Cells["SoTien"].Value != null && item.Cells["SoTien"].Value.ToString().Length > 0)
                    {
                        ct.SoTien = Convert.ToInt32(item.Cells["SoTien"].Value);
                    }
                    else
                    {
                        ct.SoTien = null;
                    }
                    if (item.Cells["DienGiai"].Value != null && item.Cells["DienGiai"].Value.ToString().Length > 0)
                    {
                        ct.DienGiai = item.Cells["DienGiai"].Value.ToString();
                    }
                    else
                    {
                        ct.DienGiai = null;
                    }
                    if (ct.TaiKhoanNo != null)
                    {
                        soTienNo += Convert.ToDecimal(ct.SoTien);
                    }
                    else if (ct.TaiKhoanCo != null)
                    {
                        soTienCo += Convert.ToDecimal(ct.SoTien);
                    }
                    co++;
                    db.Entry(ct).State = EntityState.Modified;
                }
            }
            pt.TongTien = soTienCo;
            if (soTienCo != soTienNo)
            {
                MessageBox.Show("Số phát sinh Nợ phải bằng số phát sinh Có!");
                kt = false;
            }
            if (soTienCo == 0 || soTienNo == 0)
            {
                MessageBox.Show("Dữ liệu không hợp lý!");
                kt = false;
            }
            if (soRowXoa > 0)
            {
                if (DeleteChungTuChiTiet() == false)
                {
                    kt = false;
                }
            }
            if (kt == true)
            {
                db.Entry(pt).State = EntityState.Modified;
                try
                {
                    db.SaveChanges();
                    MessageBox.Show("Chỉnh sửa thành công!");
                }
                catch (Exception e)
                {
                    MessageBox.Show(e.Message);
                }
            }
        }
        bool DeleteChungTuChiTiet()
        {
            var rtm = false;
            if (listIdChiTietCanXoa.Length > 0)
            {
                var idtam = "";
                foreach (var i in listIdChiTietCanXoa)
                {
                    if (i.ToString() == "-")
                    {
                        var tam = Convert.ToDecimal(idtam);
                        var t = db.ChungTuChiTiets.Find(tam);
                        db.ChungTuChiTiets.Remove(t);
                        idtam = "";
                    }
                    else
                    {
                        idtam += i;
                    }
                }
                try
                {
                    db.SaveChanges();
                    rtm = true;
                }
                catch (Exception e)
                {
                    MessageBox.Show("Hệ thống gặp lỗi--" + e.Message);
                    rtm = false;
                    //throw;
                }
            }
            return rtm;
        }
        void GetDataChiTietChungTu()
        {
            if (idct == "") return;
            dgvChungTuChiTiet.DataSource = db.ChungTuChiTiets.Where(t => t.ChungTuId == idct).ToList();
            dgvChungTuChiTiet.Refresh();
        }
        private void UpdateAmount(int index)
        {
            int counter;
            for (counter = 0; counter < (dgvChungTuChiTiet.Rows.Count - 1); counter++)
            {
                //kiem tra bay loi
                if (dgvChungTuChiTiet.Rows[counter].Cells["TaiKhoanNo"].Value != null || dgvChungTuChiTiet.Rows[counter].Cells["TaiKhoanCo"].Value != null)
                {
                    var tkNo = Convert.ToInt32(dgvChungTuChiTiet.Rows[counter].Cells["TaiKhoanNo"].Value);
                    var tkCo = Convert.ToInt32(dgvChungTuChiTiet.Rows[counter].Cells["TaiKhoanCo"].Value);

                    if (tkNo > 0 && tkCo > 0)
                    {
                        if (index == 2)
                        {
                            MessageBox.Show("Dữ liệu nhập không hợp lệ! Bạn chỉ co thể chọn 1 bên Nợ hoặc Có.");
                            dgvChungTuChiTiet.Rows[counter].Cells["TaiKhoanNo"].Value = null;
                        }
                        else if(index == 3)
                        {
                            MessageBox.Show("Dữ liệu nhập không hợp lệ! Bạn chỉ co thể chọn 1 bên Nợ hoặc Có.");
                            dgvChungTuChiTiet.Rows[counter].Cells["TaiKhoanCo"].Value = null;
                        }
                    }
                }
            }
        }
        #endregion Metho

        private void buttonItemPhieuChi_Click(object sender, EventArgs e)
        {
            //Views.BaoCaoChungTu.FormBaoCaoPhieuChi f=new FormBaoCaoPhieuChi(txtChungTu.Text);
            //f.ShowDialog();
        }

       

        private void btI_PhieuChi_Click_1(object sender, EventArgs e)
        {
            Views.BaoCao.FormBaoCaoPhieuChi f = new BaoCao.FormBaoCaoPhieuChi(txtChungTu.Text);
            f.ShowDialog();
        }

        private void bttThoat_Click_1(object sender, EventArgs e)
        {
            Close();
        }

      
    }
}